import {Image, StyleSheet, View, Text, TouchableOpacity, Modal, TextInput, KeyboardAvoidingView, Platform, Keyboard} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import { useState, useRef, useEffect } from "react";
import avator from "@/assets/images/me/avator.png"
import cameraIcon from "@/assets/images/me/camera.png"
import Textarea from '@/components/Textarea/index';
import { ActionSheetProvider, useActionSheet } from '@expo/react-native-action-sheet';
import * as ImagePicker from 'expo-image-picker';
import ImageViewer from 'react-native-image-zoom-viewer';
import {useDispatch, useSelector} from "react-redux";
import {AppDispatch, RootState} from "@/store";
import {getUserInfoDetail} from "@/store/slices/loginSlice";
import {editUserProfile} from "@/services/login";
import {showToast} from "@/utils/rootToast";
import axios from "axios";
import { api } from "@/config/config-params"
import { loadingService } from "@/utils/loadingServer"
import {getToken} from "@/utils";

export default function editProfileScreen() {


    const login = useSelector((state: RootState) => state.login);

    const router = useRouter();
    const { showActionSheetWithOptions } = useActionSheet();
    const nickNameRef = useRef(null);

    const dispatch = useDispatch<AppDispatch>();



    const [avatorImg, setAvatorImg] = useState<any>(login.userInfo.avatarUrl);
    const [showAvator, setShowAvator] = useState<boolean>(false)
    const [keyboardHeight, setKeyboardHeight] = useState(0);
    const [isNickNameModel, setIsNickNameModel] = useState(false);
    const [nickename, setnickname] = useState(login.userInfo.nickname);
    const [sig, setSig] = useState(login.userInfo.sign);
    const [uploadAvatorUrl, setUploadAvatorUrl] = useState("");

    useEffect(() => {
        // 在组件挂载后使 TextInput 获取焦点
        if (nickNameRef.current && isNickNameModel) {
            nickNameRef.current.focus();
        };
        if (nickNameRef.current && !isNickNameModel) {
            nickNameRef.current.blur();
        };
    }, [isNickNameModel]);

    useEffect(() => {
        dispatch(getUserInfoDetail());
    }, [])

    const pickImage = async () => {
        // Request media library permissions
        let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();

        if (permissionResult.granted === false) {
            alert('Permission to access the media library is required!');
            return;
        }

        // Open image picker
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
        });

        if (!result.canceled) {
            uploadAvator(result.assets[0]);
            // setAvatorImg(result.assets[0].uri);
        }
    };


    const openActionSheet = () => {
        const options = ['查看大图', '从手机相册选择', '取消'];
        const cancelButtonIndex = 2;

        showActionSheetWithOptions(
            {
                options,
                cancelButtonIndex,
            },
            (buttonIndex) => {
                switch (buttonIndex) {
                    case 0:
                        setShowAvator(true);
                        break;
                    case 1:
                        console.log('从手机相册选择 selected');
                        pickImage();
                        break;
                    case 2:
                        console.log('取消 selected');
                        break;
                    default:
                        break;
                }
            }
        );
    };

    const images = [{
        // Simplest usage.
        url: 'https://avatars2.githubusercontent.com/u/7970947?v=3&s=460',
    }]

    const onChangenickeName = function (text: string) {
        setnickname(text);
    };

    const onChangeSig = function (text: string) {
        setSig(text);
    };

    const postUserProfile = function (objData) {
        const data = {
            nickname: login.userInfo.nickname,
            avatarUrl: login.userInfo.avatarUrl,
            sign: login.userInfo.sign || "无",
            ...objData,
        };

        if (uploadAvatorUrl) {
            Reflect.set(data, "avatarUrl", uploadAvatorUrl)
        };

        editUserProfile(data)
            .then(res => {
                console.log('res', res);
                dispatch(getUserInfoDetail());
                showToast("保存成功！")
            })
            .catch(err => {

            })
    };

    const uploadAvator = async function (image) {
        if (!image) return;

        console.log('image', image);

        const formData = new FormData();
        formData.append('avatar', {
            uri: image.uri,
            type: image.type, // mime 类型，例如 'image/jpeg'
            name: image.fileName, // 图片名称
        });

        loadingService.show();

        const token = await getToken();

        try {
            const response = await axios.post(`${api}/account/uploadAvatar`, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    "Authorization": token,
                },
            });
            console.log('response', response.data.data);
            if (response?.data.code == 200) {
                setAvatorImg(response.data.data.url)
            } else {
                showToast(response?.data.msg)
            };

            loadingService.hide();
        } catch (error) {
            console.error('上传失败：', error);
            loadingService.hide();
        }
    };

    return (
        <TouchableOpacity style={{ height: "100%", backgroundColor: "#fff", flex: 1, }} activeOpacity={1} onPress={() => {
            Keyboard.dismiss();
        }} >
            <Stack.Screen
                options={{
                    title: '编辑资料', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#fff', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                    headerRight: () => (
                        <TouchableOpacity
                            onPress={() => {
                                const data = {
                                    sign: sig,
                                    avatarUrl: avatorImg
                                };
                                postUserProfile(data);
                            }}
                            style={{ paddingRight: 15 }}
                        >
                            <View>
                                <Text style={{ color: "#EC6138", fontSize: 14, }}>保存</Text>
                            </View>
                        </TouchableOpacity>
                    ),
                }}
            />
            <View>
                <TouchableOpacity onPress={openActionSheet}>
                    <View style={styles.avatarWarp}>
                        {
                            avatorImg ? (
                                <Image source={{ uri: avatorImg }} style={{ width: '100%', height: '100%' }}/>
                            ) : (
                                <Image source={avator} style={{ width: '100%', height: '100%' }}/>
                            )
                        }
                    </View>
                    <View style={styles.cameraIcon}>
                        <Image source={cameraIcon} style={{ width: "100%", height: "100%" }} />
                    </View>
                </TouchableOpacity>
               <TouchableOpacity onPress={() => {
                   setIsNickNameModel(true);
                   setnickname(login.userInfo.nickname);
               }}>
                   <View style={styles.nickNameWarp}>
                       <View>
                           <Text style={styles.titleText}>昵称</Text>
                       </View>
                       <View style={styles.nickNameTitle}>
                           <Text style={ styles.nickNameText }>{ login?.userInfo?.nickname }</Text>
                       </View>
                       <View>
                           <AntDesign name="right" size={11} color="#9C9EAC" />
                       </View>
                   </View>
               </TouchableOpacity>
                <View style={{ marginLeft: 12, marginTop: 36 }}>
                    <Text style={styles.signature}>个性签名</Text>
                </View>
                <View style={{ marginLeft: 12, marginTop: 12 }}>
                    <Textarea
                        maxLength={50}
                        placeholder={'简单介绍下您自己吧～'}
                        placeholderTextColor={'#c7c7c7'}
                        underlineColorAndroid={'transparent'}
                        style={ styles.signatureTextInput}
                        value={sig}
                        onChangeText={onChangeSig}
                    />
                </View>
            </View>
            <Modal
                visible={showAvator}
                transparent={true}
                onRequestClose={() => setShowAvator(false)}
                onDismiss={() => setShowAvator(false)}
            >
                <ImageViewer
                    imageUrls={ avatorImg ? [{ url: avatorImg }] : [
                        {
                            url: '',
                            props: {
                                // Or you can set source directory.
                                source: avator
                            }
                        }
                    ] }
                    enableSwipeDown
                    onSwipeDown={() => setShowAvator(false)}
                    backgroundColor={"rgba(0,0,0,0.7)"}
                    renderIndicator={(): any => null}  // 隐藏页码指示器
                    onClick={() => setShowAvator(false)}
                />
            </Modal>

            <Modal
                animationType="slide"
                transparent={true}
                visible={isNickNameModel}
            >
                <KeyboardAvoidingView
                    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                    style={styles.container}
                >
                    <View style={styles.innerContainer}>
                        <View style={styles.nikeNameContainer}>
                            <View style={{ flexDirection: "row", marginTop: 18 }}>
                                <TouchableOpacity onPress={() => setIsNickNameModel(false)}>
                                    <Text style={styles.nickHeaderCancel}>取消</Text>
                                </TouchableOpacity>
                                <Text style={styles.nickHeaderContent}>修改昵称</Text>
                                <TouchableOpacity onPress={() => {
                                    setIsNickNameModel(false);
                                    postUserProfile({ nickname: nickename })
                                }}>
                                    <Text style={styles.save}>保存</Text>
                                </TouchableOpacity>
                            </View>
                            <TextInput
                                placeholder="请输入昵称..."
                                style={styles.textInput}
                                ref={nickNameRef}
                                value={nickename}
                                onChangeText={onChangenickeName}
                            />
                        </View>
                    </View>
                </KeyboardAvoidingView>
            </Modal>
            {/*{ avatorImg && <Image source={{ uri: avatorImg }} style={{ width: 200, height: 200 }} />}*/}
        </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
    avatarWarp: {
        width: scaleSize(90),
        height: scaleSize(90),
        borderRadius: 50,
        marginTop: 42,
        margin: "auto",
        position: "relative",
        overflow: "hidden",
        // backgroundColor: "red"
    },
    cameraIcon: {
        width: scaleSize(19),
        height: scaleSize(19),
        position: "absolute",
        bottom: 2,
        right: 163,
    },
    nickNameWarp: {
        paddingLeft: 12,
        paddingRight: 12,
        flexDirection: "row",
        alignItems: "center",
        marginTop: 43,
    },
    nickNameTitle: {
        flex: 1,
        marginLeft:scaleSize(52),
    },
    titleText: {
        color: "#2A2B30",
    },
    nickNameText: {
        fontSize: 14,
        color: '#9C9EAC',
    },
    signature: {
        fontSize: 14,
        color: '#2A2B30',
    },
    signatureTextInput: {
        backgroundColor: "#F7F7F7",
        height: 100,
        padding: 12,
        fontSize: 14,
        width: scaleSize(351),
        color: "#9C9EAC",
    },

    container: {
        flex: 1,
    },
    innerContainer: {
        flex: 1,
        justifyContent: 'flex-end', // 确保输入框在底部
        backgroundColor: 'rgba(0,0,0, 0.7)',

    },
    textInput: {
        height: 38,
        // paddingHorizontal: 10,
        width: scaleSize(351),
        backgroundColor: "#F7F7F7",
        marginTop: 20,
        margin: "auto",
        paddingLeft: 15,
    },
    nikeNameContainer: {
        height: 112,
        width:scaleSize(375),
        backgroundColor: "#fff",
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10,
        paddingLeft: 10,
        paddingRight: 10,
    },
    nickHeaderCancel: {
        fontSize:  14,
        color: "#2A2B30",
    },
    nickHeaderContent: {
        fontSize: 16,
        color: "#2A2B30",
        fontWeight: "bold",
        flex: 1,
        textAlign: "center"
    },
    save: {
        fontSize: 14,
        color: "#EC6138",
    },
});
